package com.qqpz.sign_project.controller;

import com.google.gson.Gson;
import com.qqpz.sign_project.entity.User;
import com.qqpz.sign_project.service.ApiService;
import com.qqpz.sign_project.service.UserService;
import org.bouncycastle.operator.MacCalculatorProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/v1/api")
public class ApiController {
    @Autowired
    private ApiService apiService;
    @Autowired
    private UserService userService;

    @PostMapping("/{id}/upload")
    public String addFace(@PathVariable("id")String id, @RequestBody Map<String,Object> map1){
        String url=map1.get("url").toString();
        id=id.replaceAll("-","_");
        int i = 0;
        try {
            i = apiService.addFace(url, id);
        } catch (Exception e) {
            i=0;
            e.printStackTrace();
            try {
                apiService.deleteFace(id);
                User user = userService.queryUserById(id);
                user.setFace(0);
                userService.updateUserById(user);
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
        Map<String,Object> map=new HashMap<>();
        if(i!=0){
            map.put("result","success");
            return new Gson().toJson(map);
        }else{
            map.put("result","fail");
            return new Gson().toJson(map);
        }

    }

    @PostMapping("/{id}/compare")
    public String searchFace(@PathVariable("id")String id,@RequestBody Map<String,Object> map1){
        String url=map1.get("url").toString();
        id=id.replaceAll("-","_");
        int i = 0;
        try {
            i = apiService.searchFace(url, id);
        } catch (Exception e) {
            i=0;
            e.printStackTrace();
        }
        Map<String,Object> map=new HashMap<>();
        if(i!=0){
            map.put("result","success");
            return new Gson().toJson(map);
        }else{
            map.put("result","fail");
            return new Gson().toJson(map);
        }
    }

}
